package vip.kqsy.cloud.blog.server.exception;

import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import lombok.Cleanup;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import vip.kqsy.cloud.blog.server.res.BlogRCodeEm;
import vip.kqsy.cloud.core.common.util.JsonUtil;
import vip.kqsy.cloud.core.web.res.R;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

@Component
@Slf4j
public class BlogExceptionHandler implements BlockExceptionHandler {
    @Override
    public void handle(HttpServletRequest httpServletRequest, HttpServletResponse
            httpServletResponse, BlockException e) throws Exception {
        log.error("限流", e);
        httpServletResponse.setContentType("application/json;charset=utf-8");
        @Cleanup
        PrintWriter writer = httpServletResponse.getWriter();
        writer.print(JsonUtil.toJson(R.error(BlogRCodeEm.BLOCK)));
    }
}
